const { schema } = require("../pipe/article")

/**
 * @type {Custom.Controller}
 */
module.exports = {
    async index(ctx, next) {
        const {
            limit,
            page,
            type
        } = await schema.index.validateAsync(ctx.query)

        const offset = limit * (page - 1) //定义偏移量从0开始所以要减去1  后端都素offset

        const articles = await ctx.model.Article.findAndCountAll({
            limit,
            offset,
            order: [
                ["id", "DESC"]
            ],
            where: { type }
        })
        ctx.success(articles)
        await next()
    },
    async show(ctx, next) {
        const { id } = await schema.show.validateAsync(ctx.params)
            //找相应的文章
        const article = await ctx.model.Article.findByPk(id, {
            //还要拿到作者的信息
            include: {
                model: ctx.model.User,
                //密码也要排掉
                attributes: { exclude: ["password"] }
            }
        })
        ctx.success(article)
            //没有找到返回一个信息
        if (!article) {
            return ctx.success("文章未找到，请确认文章id", 404)
        }
    },
    async create(ctx, next) {
        const { id: user_id } = ctx.state.user
        const newInfo = await schema.create.validateAsync(
            ctx.request.body
        )
        const article = await ctx.model.Article.create({
            ...newInfo,
            UserId: user_id
        })

        ctx.success(article)
        await next()
    },
    async update(ctx, next) {
        // ctx.success("测试")拿到user的id
        const { id: user_id } = ctx.state.user
            //做校验
        const { id, ...newInfo } = await schema.update.validateAsync({
                ...ctx.params,
                ...ctx.request.body
            })
            //做了后找一找文章在不在
        const article = await ctx.model.Article.findByPk(id)

        //没找到返回一个信息
        if (!article) {
            return ctx, fail("更新文章失败，文章未找到，请确认文章id", 400)
        }
        //如果找到了就判断文章id是不是查找的user_id
        const userIdIsEqual = article.UserId === user_id
        if (!userIdIsEqual) {
            return ctx.fail("该用户无权限更新此文章", 401)
        }
        //然后做一个更新的操作
        await article.update(newInfo)
        ctx.success(article, 201)
        await next()
    },
    async destroy(ctx, next) {
        // ctx.success("测试")拿到user的id
        const { id: user_id } = ctx.state.user
            //校验
        const { id } = await schema.destroy.validateAsync(ctx.params)
            //有的话判断是否存在文章
        const article = await ctx.model.Article.findByPk(id)
        if (!article) {
            return ctx.fail("删除失败，文章未找到，请确认文章id")
        }
        //如果找到了就判断文章id是不是查找的user_id
        const userIdIsEqual = article.UserId === user_id
        if (!userIdIsEqual) {
            return ctx.fail("该用户无权限删除此文章", 401)
        }
        //然后做一个销毁的操作
        await article.destroy()
        ctx.success(null, 204)
        await next()
    }
}